<?php
/*覃小华开发 QQ：735560936*/
require_once(dirname(__FILE__)."/config.php");
if(empty($action)) $action = '';
if($cfg_mb_allowreg=='N')
{
    ShowMsg('暂停新用户注册', $cfg_basehost);
    exit();
}
if($cfg_ml->IsLogin())
{
    ShowMsg('您已经登录系统', $cfg_basehost);
    exit();
}
if($action == 'oauth')
{
	$type = empty($_REQUEST['type']) ?  '' : $_REQUEST['type'];
	include_once(dirname(__FILE__).'/oauth.php');
	$c = &website($type);
	if($c)
	{
		$back_act = $GLOBALS['_SERVER']['HTTP_REFERER'];
		$open = empty($_REQUEST['open']) ? 0 : intval($_REQUEST['open']);
        $tz = trim($_REQUEST['tz']);
		
		if(!empty($tz)){
		    $back_act =  urldecode($tz);
		}
		$url = $c->login($cfg_basehost.'/oauth/index_do.php?action=oauth_login&type='.$type.'&callblock='.urlencode($back_act).'&open='.$open);
		if(!$url)
		{
			ShowMsg($c->get_error(), '-1');
		}
		header('Location: '.$url);
	}
	else
	{
		ShowMsg('未配置的登录插件', $cfg_basehost);
	}
}
elseif($action == 'oauth_login')
{
	$type = empty($_REQUEST['type']) ?  '' : $_REQUEST['type'];
	$callblock = empty($_REQUEST['callblock']) ?  '/index.php' : urldecode($_REQUEST['callblock']);
	include_once(dirname(__FILE__).'/oauth.php');
	$c = &website($type);
	if($c)
	{
		$access = $c->getAccessToken();
		if(!$access)
		{
			ShowMsg($c->get_error(), '-1');
		}
		$c->setAccessToken($access);
		$info = $c->getMessage();
		if(!$info)
		{
			ShowMsg($c->get_error(), '-1');
		}
		if(!$info['openid'])
		{
			ShowMsg($c->get_error(), '-1');
		}
		$userid = $info['openid'];
		$face = str_replace('http:', '', $info['face']);
		
		if($cfg_soft_lang == 'gb2312')
		{
			$uname = utf82gb($info['uname']);
			$sex = utf82gb($info['sex']);
		}
		else
		{
			$uname = $info['uname'];
			$sex = $info['sex'];
		}
		if($cfg_ml->IsLogin())
		{
			ShowMsg('您已经登录系统', $callblock,0,1000);
			exit();
		}
		$memInfo = $dsql->GetOne("SELECT * FROM #@__member WHERE `wx_openid` = '{$userid}'");
		$jointime = time();
		$logintime = time();
		$joinip = GetIP();
		$loginip = GetIP();
		if(empty($memInfo) && !empty($userid))
		{
			$mid = AutoRegMember($userid, $uname, $face, $sex);
			if($mid)
			{
				$cfg_ml->PutLoginInfo($mid);
				$cfg_ml->DelCache($mid);
				ShowMsg("登录成功，正在加载中...",$callblock,0,2000);
				exit;
			}
		}
		else
		{
			$cfg_ml->PutLoginInfo($memInfo['mid']);
			$cfg_ml->DelCache($cfg_ml->M_ID);
			ShowMsg("登录成功，正在加载中...",$callblock,0,2000);
			exit;
		}
	}
}
else
{
    ShowMsg("本页面禁止返回!",$cfg_basehost);
}